<template>
    <el-dialog v-model="updateDialogVisible" title="修改用户密码" width="500">
        <el-form ref="ruleForm" :rules="rules" :model="updateUserPasswordData">
            <el-form-item label="密码：" prop="oldPassword" required>
                <el-input id="pwd1" type="password" v-model="updateUserPasswordData.oldPassword" autocomplete="off" placeholder="请输入密码"/>
                <el-icon style="position: absolute; left: 90%;color: seagreen;">
                    <template v-if="isEye1"><View @click="toEye(1)"/> </template>
                    <template v-if="!isEye1"><Hide @click="toEye(1)"/></template>
                </el-icon>
            </el-form-item>
            <el-form-item label="确认密码：" prop="rightPassword" required>
                <el-input id="pwd2" type="password" v-model="updateUserPasswordData.rightPassword" autocomplete="off" placeholder="请再次输入密码"/>
                <el-icon style="position: absolute; left: 90%;color: seagreen;">
                    <template v-if="isEye2"><View @click="toEye(2)"/> </template>
                    <template v-if="!isEye2"><Hide @click="toEye(2)"/></template>
                </el-icon>
            </el-form-item>
            <el-form-item label="新密码：" prop="newPassword" required>
                <el-input id="pwd3" type="password" v-model="updateUserPasswordData.newPassword" autocomplete="off" placeholder="请输入新密码"/>
                <el-icon style="position: absolute; left: 90%;color: seagreen;">
                    <template v-if="isEye3"><View @click="toEye(3)"/> </template>
                    <template v-if="!isEye3"><Hide @click="toEye(3)"/></template>
                </el-icon>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="updateDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="updateUserPasswordMsg(ruleForm)">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref,onMounted } from 'vue';
import { useRouter } from 'vue-router';
import type { FormRules, FormInstance} from 'element-plus'
import { updateUserPassword } from "@/api/login";
import {ElMessage } from 'element-plus';
import {useGlobStore} from '@/stores/useGlobStore'
import { storeToRefs} from 'pinia'
import { Md5 } from 'ts-md5'

const store = useGlobStore();
const {isUpdatePassword} = storeToRefs(store);

const userMsg = ref({id:'',userName:'',password:''});
const isEye1 = ref(false);
const isEye2 = ref(false);
const isEye3 = ref(false);
const updateDialogVisible = ref(isUpdatePassword);
const router = useRouter();
const updateUserPasswordData = ref({oldPassword:'',rightPassword:'',newPassword:''})
const ruleForm = ref();

const checkPassword = (rule: any, value: any, callback: any) => {
  console.log(userMsg.value.password);
  console.log(Md5.hashStr(value));
  if (value === '') 
  {
    callback(new Error('密码不能为空'))
  } 
  else if(Md5.hashStr(value) !== userMsg.value.password)
  {
    callback(new Error('与旧密码不一致'))
  }
  else 
  {
    callback()
  }
}
const checkRightPassword = (rule: any, value: any, callback: any) => {
    if (value === '') 
    {
        callback(new Error('密码不能为空'))
    } 
    else if(value!==updateUserPasswordData.value.oldPassword)
    {
        callback(new Error('与密码不一致'))
    }
    else 
    {
        callback()
    }
}
const checkNewPassword  = (rule: any, value: any, callback: any) => {
    if (value === '') 
    {
        callback(new Error('密码不能为空'))
    } 
    else if(value.length>12||value.length<5)
    {
        callback(new Error('密码长度为5-12位'))
    }
    else 
    {
        callback()
    }
}

const rules = ref<FormRules<typeof updateUserPasswordData>>({
  oldPassword: [{ validator: checkPassword, trigger: 'blur' }],
  rightPassword: [{ validator: checkRightPassword, trigger: 'blur' }],
  newPassword: [{ validator: checkNewPassword, trigger: 'blur' }],
})

const init = ()=> {
    userMsg.value = JSON.parse(String(localStorage.getItem("dsUser")))
    router.push("/home");
}

//更新用户密码
const updateUserPasswordMsg = (formName:FormInstance|undefined)=>{
    if(!formName) return;
    formName.validate((valid) =>{
      if(valid) 
      {
        let formData = new FormData();
        let userPassData = {id:userMsg.value.id,password:Md5.hashStr(updateUserPasswordData.value.newPassword)};
        formData.append('user',JSON.stringify(userPassData));
        updateUserPassword(formData)
        .then((res:any) => {
            if (String(res.data.code) === '1') 
            {
                ElMessage.success("修改成功");
                localStorage.removeItem('psptToken');
                localStorage.removeItem('dsUser');
                localStorage.removeItem('globStore');
                router.push("/home");
            }
            else
            {
              ElMessage.error(res.data.msg);
            }})
          .catch((err:any) => console.log(err))
      }
    }
  )
}

onMounted(() =>{init()})

function toEye(num:number)
{
  let doc = null;
  let is = false;
  if(num===1)
  {
    isEye1.value = !isEye1.value;
    is = isEye1.value;
    doc = document.getElementById('pwd1')
  }
  else if(num===2)
  {
    isEye2.value = !isEye2.value;
    is = isEye2.value;
    doc = document.getElementById('pwd2')
  }
  else
  {
    isEye3.value = !isEye3.value;
    is = isEye3.value;
    doc = document.getElementById('pwd3')
  }
  if(is) 
  {
    doc!.setAttribute('type','text');
  }
  else
  {
    doc!.setAttribute('type','password');
  }
}
</script>
  
<style>
.dialog-footer
{
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center
}
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
  height: 100%;
}
</style>
